import 'dart:convert';
import 'dart:io';

import 'package:get/get.dart';
import 'package:m6/Public/model/language_config.dart';
import 'package:m6/Untils/api.dart';
import 'package:m6/Untils/request.dart';
import 'package:path_provider/path_provider.dart';

class AppManager extends GetxController {
  var isLogin = true.obs;
  var config = LanguageConfig().obs;
  var session = "";

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    getLanguageConfig();
  }

  Future<void> getLanguageConfig() async {
    CustomerResponse response = await Request.get(URL_Page_Setting, null);
    if (response.code == 1) {
      final config =
          LanguageConfig.fromJson(response.data as Map<String, dynamic>);
      this.config.value = config;

      File file = await documentFile("language_config.text");
      if (await file.exists() == false) {
        await file.create();
      }
      file.writeAsString(response.data.toString());
    } else {
      File file = await documentFile("language_config.text");
      if (await file.exists() == false) {
        return;
      }
      final string = await file.readAsString();
      final config = LanguageConfig.fromJson(jsonDecode(string));
      this.config.value = config;
    }
    update();
  }

  Future<File> documentFile(String fileName) async {
    final fileDirectory = await getApplicationDocumentsDirectory();
    final filePath = fileDirectory.path;
    return File("$filePath/$fileName");
  }
}
